<?php

require_once 'PipesImpl/Config.php';

class Pipes_Database_Sequence
{
	private $_pdo = null;
	private $_created = false;
	
	public function __construct(PipesImpl_Config $config) {
		$this->_pdo = $config->pdo;
		
		if ($this->_select() === false) {
			$this->_created = true;
			$this->_pdo->exec('CREATE TABLE sequences (id INT(11) auto_increment PRIMARY KEY)');
			$this->_pdo->exec('INSERT INTO sequences VALUES (null)');
		}
	}
	
	public function next() {
		if ($this->_created) {
			$this->_created = false;
			return $this->_select();
		}
		
		$this->_update();
		return $this->_select();
	}
	
	private function _update() {
		$updateSql = "UPDATE sequences SET id = id + 1";
		$this->_pdo->exec($updateSql);		
	}
	
	private function _select() {
		$selectSql = 'SELECT * FROM sequences';
		$result = $this->_pdo->query($selectSql);
		if ($result === false) {
			return false;
		} else {
			return (int) array_shift($result->fetch());
		}
	}
}
